﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Meqs.Entity;
using Meqs.Logic.Interface;
using System.Collections.Generic;
using Meqs.Utilities;

public partial class Base_School_StudentGridUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            collomType.Value = "0";
            Hashtable table = new Hashtable();
            table.Add("SchoolMark", Common.GetConstSchoolMark());
            table.Add("IsEffect", true);
            table.Add("ClsID", GetClassID);
            SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
            IStudentHistoryLogic studentLogic = Container<IStudentHistoryLogic>.Instance;
            List<StudentInfo> list = (List<StudentInfo>)studentLogic.FindHistoryStudents(si.SchoolYear,si.SchoolTerm,GetClassID,Common.GetConstSchoolMark());
            foreach(StudentInfo stu in list)
            {
                StudentsInfos += "<tr>";
                StudentsInfos += "<td  style='text-align:left'>";
                StudentsInfos += stu.StudentCode;
                StudentsInfos += "</td>";

                StudentsInfos += "<td  style='text-align:left'>";
                StudentsInfos += stu.StudentName;
                StudentsInfos += "</td>";

                StudentsInfos += "<td  style='text-align:left'>";
                StudentsInfos += stu.Sexy == 0 ? "男" : "女";
                StudentsInfos += "</td>";

                StudentsInfos += "<td  style='text-align:left'>";
                StudentsInfos += stu.Birthday.Year > 2030 ? "" : stu.Birthday.ToString("yyyy-MM-dd");
                StudentsInfos += "</td>";

                StudentsInfos += "<td  style='text-align:left'>";
                StudentsInfos += stu.InSchoolDate.Year > 2030 ? "" : stu.InSchoolDate.ToString("yyyy-MM-dd");
                StudentsInfos += "</td>";

                StudentsInfos += "</tr>";
            }
        }
    }
    private int GetClassID
    {
        get
        {
            string grade = Request.QueryString["clsid"];
            int temp = 0;
            if (int.TryParse(grade, out temp))
            {
                return temp;
            }
            return 0;
        }
    }
    protected string StudentsInfos = "";
    protected void btnReqClsOK_ServerClick(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                //  保存文件
                DataSet ds = Meqs.Utilities.ExcelUtil.ExcelImport1(FileUpload1.PostedFile.InputStream);
                if (ds.Tables.Count > 0)
                {
                    string info = "";
                    ClsInfo cls = Container<IClsInfoLogic>.Instance.FindById(GetClassID);
                    SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
                    if (collomType.Value == "0")
                    {
                        info = DoCode(ds.Tables[0], cls, si);
                    }
                    else
                    {
                        info = DoName(ds.Tables[0], cls, si);
                    }

                    if (info.Length > 0)
                    {
                        Response.Write("<script>parent.HaveDone(2,'" + info + "')</script>");
                    }
                    else
                    {
                        Response.Write("<script>parent.HaveDone(1,'')</script>");
                    }
                }
                else
                {
                    //错误文件
                    Response.Write("<script>parent.HaveDone(2,'无法获取数据，请使用模版进行填报！')</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("<script>parent.HaveDone(2,'" + ex .Message+ "')</script>");
            }
        }
        else
        {
            Response.Write("<script>parent.HaveDone(2,'文件错误！')</script>");
        }

    }
    /// <summary>
    /// 根据学号更新
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="cls"></param>
    /// <returns></returns>
    private string DoCode(DataTable dt,ClsInfo cls,SchoolInfo si)
    {
        string str = "";
        string str1 = "";
        string str2 = "";
        //将本班所有学生设为无效
        //本学期本班学生存在历史信息删除
        Container<IClassHistoryLogic>.Instance.UpdateOneClassStuinfo(cls.RID, si.SchoolYear, si.SchoolTerm);
        int clsindex = 0;
        foreach (DataRow row in dt.Rows)
        {
            try
            {
                if (string.IsNullOrEmpty(GetInfo(row[0])) || string.IsNullOrEmpty(GetInfo(row[1])))
                    continue;
                Hashtable ht = new Hashtable();
                ht.Add("FullStuCode", GetInfo(row[0]));
                IList<StudentInfo> stus = Container<IStudentInfoLogic>.Instance.FindAll(ht);
                if (stus.Count == 1)
                {
                    if (stus[0].ClsID != cls.RID)
                    {
                        str1 += stus[0].StudentCode + "(" + stus[0].StudentName + ")" + ",";
                    }
                    //匹配学生学号，更新信息，注意忽略掉学号重复情况
                    stus[0].ClsID = cls.RID;
                    stus[0].StudentName = GetInfo(row[1]);
                    stus[0].Sexy = GetInfo(row[2]) == "男" ? (short)0 : (short)1;
                    stus[0].Birthday = FormatTime(GetInfo(row[3]));
                    stus[0].InSchoolDate = FormatTime(GetInfo(row[4]));
                    stus[0].IsEffect = true;
                    stus[0].ClsIndex = clsindex;
                    
                    Container<IStudentInfoLogic>.Instance.Update(stus[0]);

                    ht.Clear();
                    ht.Add("StudentID", stus[0].RID);
                    ht.Add("SchoolYear", si.SchoolYear);
                    ht.Add("Term", si.SchoolTerm);
                    if (Container<IStudentHistoryLogic>.Instance.FindAll(ht).Count > 0)
                    {
                        Container<IStudentHistoryLogic>.Instance.DeleteStudentHistory(ht);
                    }
                    StudentHistory sh = new StudentHistory();
                    sh.ClassID = cls.RID;
                    sh.Grade = cls.Grade;
                    sh.SchoolYear = si.SchoolYear;
                    sh.StudentID = stus[0].RID;
                    sh.Term = si.SchoolTerm;
                    Container<IStudentHistoryLogic>.Instance.Create(sh);
                    clsindex++;
                }

                if (stus.Count == 0)
                {
                    str2 += GetInfo(row[0]) + "(" + GetInfo(row[1]) + ")" + ",";
                    //若原来不存在这个学号的学生视为新增。
                    StudentInfo stuinfo = new StudentInfo(-1, GetInfo(row[0]), GetInfo(row[1]), "123456", GetInfo(row[2]) == "男" ? (short)0 : (short)1, FormatTime(GetInfo(row[3])), FormatTime(GetInfo(row[4])), cls.RID, true, Common.GetConstSchoolMark());
                    stuinfo.ClsIndex = clsindex;
                    stuinfo.RID = Container<IStudentInfoLogic>.Instance.Create(stuinfo);
                    StudentHistory sh = new StudentHistory();
                    sh.ClassID = cls.RID;
                    sh.Grade = cls.Grade;
                    sh.SchoolYear = si.SchoolYear;
                    sh.StudentID = stuinfo.RID;
                    sh.Term = si.SchoolTerm;
                    Container<IStudentHistoryLogic>.Instance.Create(sh);
                    clsindex++;
                }
            }
            catch
            {
                continue;
            }
        }
        if (str1.Length > 0)
        {
            str1 = "转入班级学生:<br/>" + str1 + "<br/>";
        }
        if (str2.Length > 0)
        {
            str2 = "班级新增学生:<br/>" + str2;
        }
        //填写学生 所在班级的学生历史信息。
        return str1 + str2;
    }
    /// <summary>
    /// 根据名字更新
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="cls"></param>
    /// <returns></returns>
    private string DoName(DataTable dt, ClsInfo cls, SchoolInfo si)
    {
        string str = "";
        //查处这个班当前所有的学生信息。
        IList<StudentInfo> studs = Container<IStudentHistoryLogic>.Instance.FindHistoryStudents(si.SchoolYear, si.SchoolTerm, cls.RID, si.SchoolMark);
        //根据名字进行匹配
        foreach (DataRow row in dt.Rows)
        {
            if (string.IsNullOrEmpty(GetInfo(row[0])) || string.IsNullOrEmpty(GetInfo(row[1])))
                continue;
            try
            {
                int clsindex = 0;
                foreach (StudentInfo stu in studs)
                {
                    if (GetInfo(row[1]) == stu.StudentName.Replace(" ",""))
                    {
                        if (string.IsNullOrEmpty(GetInfo(row[0])) || string.IsNullOrEmpty(GetInfo(row[1])))
                            continue;

                        if (stu.StudentCode != GetInfo(row[0]))
                        {
                            Hashtable ht = new Hashtable();
                            ht.Add("FullStuCode", GetInfo(row[0]));
                            IList<StudentInfo> ss = Container<IStudentInfoLogic>.Instance.FindAll(ht);
                            if (ss.Count > 0)
                            {

                                str += GetInfo(row[1]) + ",";
                                continue;
                            }
                        }

                        stu.StudentCode = GetInfo(row[0]);
                        stu.Sexy = GetInfo(row[2]) == "男" ? (short)0 : (short)1;
                        stu.Birthday = FormatTime(GetInfo(row[3]));
                        stu.InSchoolDate = FormatTime(GetInfo(row[4]));
                        stu.IsEffect = true;
                        stu.ClsIndex = clsindex;
                        Container<IStudentInfoLogic>.Instance.Update(stu);
                        clsindex++;
                    }
                }
            }
            catch
            {
                continue;
            }

        }
        if (str.Length > 0)
        {
            str = "新学号与他人重复无法更新:<br/>" + str;
        }
        //进行更新信息。
        return str;
    }

    private string GetInfo(object obj)
    {
        if (obj is DBNull)
        {
            return "";
        }
        return obj.ToString().Replace(" ","");
    }

    private DateTime FormatTime(string times)
    {
        DateTime t = DateTime.Now;
        try
        {
             t= Convert.ToDateTime(times);
        }
        catch
        {
             t = DateTime.MaxValue;
        }
        return t;
    }
    [System.Web.Services.WebMethod]
    public static string GetExcel(int clsid, ExcelTableCell[][] cells)
    {
        ClsInfo clsinfo = Container<IClsInfoLogic>.Instance.FindById(clsid);
        if (clsinfo != null)
        {
            string temp_path = HttpContext.Current.Server.MapPath("../../");
            string save_path = temp_path + "download\\班级导入信息" + DateTime.Now.Ticks.ToString() + ".xls";
            HttpContext.Current.Session["filepath"] = save_path;
            ExcelUtil.ExcelExport(save_path, clsinfo.ClsName + "学生信息导入", 1, 0, cells);
        }
        return "";
    }
}
